why does array initialization in function other than main is temporary? [on hold]

Posted by shafeeq on Programmers See other posts from Programmers or by shafeeq
Published on 2013-06-28T06:04:25Z Indexed on 2013/06/28 10:29 UTC
Read the original article Hit count: 195

Filed under:
|
|
|

This is the code in which i initialize array "turn[20]" in main as well as in function "checkCollisionOrFood()",the four values turn[0],turn[1],turn[2],turn[3] are initialized to zero in main function,rest are being intialized in "checkCollisionOrFood()".This is where fault starts.when i initialize turn[4]=0 in "checkCollisionOrFood()" and then access it anywhere,it remains 0 in any function,but! when i initialize next turn[] i.e turn[5],the value of turn[4] gets depleted .i.e turn[4] have garbage value.turn[20] is global variable,its index"head" is also global.I'm stuck.Plz help me get out of it.Ishall be highly obliged for this act of kindness.This is my excerpt of code

unsigned short checkCollisionOrFood(){
head=(head+1)%20;
if(turn[head-1]==0){
    turn[head]=0;

/this is where turn[] is iniliazized and if i access turn[head] here i.e just after iniliazition then it gives correct value but if i access its previous value means turn[head-1]then it gives garbage value/

    rowHead=(rowHead+1)%8;
    if(!(address[colHead]&(1<<rowHead)))return 1;
    else if((address[colHead]&(1<<rowHead))&&
    (!((colHead==foody)&&(rowHead==foodx))))gameOver();
    else return 0;
    }
if(turn[head-1]==1){
    turn[head]=1;
    colHead=(colHead+1)%8;
    if(!(address[colHead]&(1<<rowHead)))return 1;
    else if((address[colHead]&(1<<rowHead))&&
    (!((colHead==foody)&&(rowHead==foodx))))gameOver();
    else return 0;
    }
}

void main(void)

{ turn[0]=0;turn[1]=0;turn[2]=0;turn[3]=0; /these values of turn[] are not changed irrespective of where they are accessed./

while (1)
  {
  if(checkCollisionOrFood())
    {
    PORTB=(address[colHead] |=1<<rowHead);
    turnOffTail();
    blink();
    }
  else
    {
    PORTB=address[colHead];
    createFood();
    blink();
    }
  }
}

Plz help me.

© Programmers or respective owner

Related posts about c

    Related posts about array